package com.share.beta.web;

import com.alibaba.fastjson.JSONObject;
import com.share.common.utils.HttpUtil;
import com.share.common.utils.StrUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 01401061 - 孙艳强
 * @date 2020/12/10 14:13
 */
@Slf4j
@RestController
@RequestMapping(DispatchController.PREFIX)
public class DispatchController {
    public static final String PREFIX = "dispatch";

    @Value("${rootUrl.proxy:null}")
    private String rootProxyUrl;

    @ApiOperation("get请求参数参数本来就在URL,因此只需要发请求即可")
    @GetMapping("/**")
    public Object get(HttpServletRequest request) {
        String requestUrl = buildRequestUrl(request);
        Map<String, String> headers = buildHeaders();
        try {
            return HttpUtil.get(requestUrl, null, headers);
        } catch (Exception e) {
            log.error("请求转发异常,url=" + requestUrl, e);
            return null;
        }
    }

    @ApiOperation("post请求转发")
    @PostMapping("/**")
    public Object post(HttpServletRequest request, @RequestBody JSONObject params) {
        String requestUrl = buildRequestUrl(request);
        Map<String, String> headers = buildHeaders();
        try {
            return HttpUtil.postForm(requestUrl, params, headers);
        } catch (Exception e) {
            log.error("请求转发异常,url={}", requestUrl, e);
            return null;
        }
    }

    private String buildRequestUrl(HttpServletRequest request) {
        String result = null;
        String requestURL = request.getRequestURL().toString();
        final String prefix = StrUtil.trim(PREFIX, '/');
        int index = -1;
        if (!StringUtils.isEmpty(prefix) && (index = requestURL.indexOf(prefix)) >= 0) {
            String uri = requestURL.substring(index + prefix.length());
            uri = StrUtil.trim(uri, '/');
            return rootProxyUrl + "/" + uri;
        } else {
            String requestURI = request.getRequestURI();
            return rootProxyUrl + "/" + requestURI;
        }
    }

    private Map<String, String> buildHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("requestWay", "dispatch");
        return headers;
    }
}
